package birdsong.dummy;

import java.util.ArrayList;
import java.util.List;

import birdsong.comm.ServerComm;
import birdsong.comm.ServerSideMessage;
import birdsong.server.BirdsongServer;

public class BirdsongServerDummy implements BirdsongServer {
    private List<String> connectedClients;

    public BirdsongServerDummy() {
	connectedClients = new ArrayList<String>();
    }

    @Override
    public void start(ServerComm serverComm) {
	serverComm.start();

	while (true) {
	    ServerSideMessage message = serverComm.getNextMessage();

	    switch (message.getType()) {
	    case CLIENT_CONNECTED:
		// notificar todos os clientes ja ligados que ha um novo cliente
		String newClientNickname = message.getClientNickname();
		for (String nickName : connectedClients) {
		    if (nickName != newClientNickname) {
			serverComm.sendClientConnected(nickName, newClientNickname);
		    }
		}
		connectedClients.add(message.getClientNickname());
		break;
	    case CLIENT_DISCONNECTED:
		// Passar mensagem para servidor
		String clientDisconnectedNickname = message.getClientNickname();
		for (String nickName : connectedClients) {
		    if (!nickName.equalsIgnoreCase(clientDisconnectedNickname)) {
			serverComm.sendClientDisconnected(nickName, clientDisconnectedNickname);
		    }
		}
		connectedClients.remove(message.getClientNickname());
		break;
	    case BIRDSONG_MESSAGE:
		// Passar mensagem para servidor
		String birdSongMessage = message.getPayload();
		String clientSendingMessage = message.getClientNickname();
		for (String nickName : connectedClients) {
		    if (!nickName.equalsIgnoreCase(clientSendingMessage)) {
			serverComm.sendBirdsongMessage(clientSendingMessage, nickName, birdSongMessage);
		    }
		}
		break;
	    case FOLLOW:
		// Passar mensagem para servidor
		String nicknameTofollow = message.getPayload();
		String clientNickname = message.getClientNickname();
		serverComm.sendNewFollower(nicknameTofollow, clientNickname);
		break;
	    case UNFOLLOW:
		// Passar mensagem para servidor
		String nicknameToUnfollow = message.getPayload();
		String clientNick = message.getClientNickname();
		serverComm.sendNewUnfollow(nicknameToUnfollow, clientNick);
		break;
	    default:
		break;
	    }
	}
    }

}
